<template>
  <div class="loginpage">
    <div class="reset-password">
      <div class="resetmain">
        <div class="back-icon" @click="router.push('/login')">
          <van-icon name="arrow-left" size="20" color="#f6eade" />
        </div>
        <div class="mt-2 login-title">
          <h3>{{t('logintxt.forgot01')}}</h3>
        </div>
        <div class="reset-form">
          <van-form :model="postData" :validate-trigger="[]" @submit="reset">
            <div class="overflow-hidden rounded-3xl phone-input-wrapper">
              <div class="user-icon-container mb-5">
                <img src="@/assets/images/login/iconUser.png" class="user-icon" alt="user icon" />
              </div>
              <div class="phone-area-code" @click="showAreaCodePicker = true">
                <span>+{{ currentAreaCode }}</span>
                <van-icon name="arrow-down" size="14" />
              </div>
              <van-field v-model="postData.tel" name="tel" 
                :placeholder="t('logintxt.forgot01')" class="phone-input" :formatter="removeSpace" />
            </div>

            <div class="mt-16 overflow-hidden rounded-3xl verification-input-wrapper">
              <div class="verification-icon-container mb-5">
                <van-icon name="shield-o" size="18" color="#f6eade" />
              </div>
              <van-field v-model.trim="postData.code" name="code"
              :placeholder="t('logintxt.register03')" class="verification-input">
                <template #right-icon>
                  <div 
                    class="send-code-btn" 
                    @click="getCode" 
                    :class="{ 'disabled': countdown > 0 }"
                  >
                    {{ countdownText }}
                  </div>
                </template>
              </van-field>
            </div>
            <!-- 提示 -->
            <div class="fortips">
              <span>{{ t('logintxt.forgotword01') }}</span>
            </div>
            <div class="mt-16 overflow-hidden rounded-3xl">
              <van-field 
                v-model="postData.loginPassword" 
                :type="showPassword ? 'text' : 'password'" 
                name="loginPassword"
                :placeholder="t('logintxt.forgot03')"
                :formatter="removeSpace"
                class="password-input"
              >
                <template #left-icon>
                  <div class="password-icon-container">
                    <img src="@/assets/images/login/iconPass.png" class="password-icon mb-5" alt="password icon" />
                  </div>
                </template>
                <template #right-icon>
                  <van-icon 
                    :name="showPassword ? 'eye-o' : 'closed-eye'" 
                    size="20" 
                    @click="showPassword = !showPassword" 
                    color="#f6eade"
                  />
                </template>
              </van-field>
            </div>

            <div class="mt-16">
              <van-button 
                :loading="loading" 
                native-type="submit" 
                round 
                block 
                class="reset-btn"
              >
                {{t('logintxt.forgot01')}}
              </van-button>
            </div>
          </van-form>
        
          <div class="privacy-policy-container">
            <router-link to="/privacy-policy" class="privacy-policy-link">
              {{t('logintxt.login09')}}
            </router-link>
          </div>
        </div>

        <!-- 区号选择弹窗 -->
        <van-popup v-model:show="showAreaCodePicker" position="bottom" round>
          <van-picker
            :title="t('logintxt.login10')"
            :columns="areaCodeOptions"
            @confirm="onAreaCodeConfirm"
            @cancel="showAreaCodePicker = false"
            show-toolbar
          />
        </van-popup>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { areaCodeApi, verifyResetCode } from '@/api/login'
import { useUserStore } from '@/stores'
import { showDialog, showNotify } from 'vant'
import { onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'

const { t } = useI18n()
const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const showPassword = ref(false)
const showAreaCodePicker = ref(false)

// 区号选择配置 - 改为动态获取
const areaCodeOptions = ref([
  { text: '+57', value: '57' },
])

// 当前选中的区号
const currentAreaCode = ref('57')

// 获取区号列表
async function getAreaCodes() {
  try {
    const { data } = await areaCodeApi()
    if (data && Array.isArray(data)) {
      // 将API返回的区号数据转换为选择器需要的格式
      areaCodeOptions.value = data.map((item: any) => {
        return {
          text: `${item.country || ''} +${item.mobilePrefix}`,
          value: item.mobilePrefix
        }
      })
      
      // 如果用户没有选择区号，则设置默认区号
      if (!postData.areaCode && areaCodeOptions.value.length > 0) {
        const defaultOption = areaCodeOptions.value[0];
        postData.areaCode = defaultOption.value;
        currentAreaCode.value = defaultOption.value;
      }
    }
  } catch (error) {
    console.error('err:', error)
    // 确保至少有一个默认选项
    if (areaCodeOptions.value.length === 0) {
      areaCodeOptions.value = [{ text: '+57', value: '57' }];
      if (!postData.areaCode) {
        postData.areaCode = '57';
        currentAreaCode.value = '57';
      }
    }
  }
}

function removeSpace(value: string) {
  return value.replace(/\s+/g, "");
}

function onAreaCodeConfirm(result: any) {
  console.log(result);
  
  // 处理新的选择器返回格式
  if (result.selectedOptions && result.selectedOptions.length > 0) {
    // 新格式
    const selectedOption = result.selectedOptions[0];
    postData.areaCode = selectedOption.value;
    currentAreaCode.value = selectedOption.value;
  } else if (result.value) {
    // 旧格式兼容处理
    postData.areaCode = result.value;
    currentAreaCode.value = result.value;
  }
  
  showAreaCodePicker.value = false;
}

const postData = reactive({
  areaCode: currentAreaCode.value, // 默认印度尼西亚区号
  tel: '',
  code: '',
  loginPassword: '',
})

// 使用自定义验证函数，而不是规则数组
function validatePhoneNumber() {
  if (!postData.tel) {
    showDialog({
      message: t('logintxt.login02'),
      confirmButtonText: t('logintxt.register07'),
      confirmButtonColor: '#3f88f5',
      className: 'custom-dialog',
      showCancelButton: false,
      closeOnClickOverlay: true
    })
    return false
  }
  
  // 添加电话号码格式验证
  const phoneRegex = /^\d{9,12}$/ // 9-12位数字
  if (!phoneRegex.test(postData.tel)) {
    showDialog({
      message: t('logintxt.register08'),
      confirmButtonText: t('logintxt.register07'),
      confirmButtonColor: '#3f88f5',
      className: 'custom-dialog',
      showCancelButton: false,
      closeOnClickOverlay: true
    })
    return false
  }
  
  return true
}

function validateCode() {
  if (!postData.code) {
    showDialog({
      message: t('logintxt.forgot09'),
      confirmButtonText: t('logintxt.register07'),
      confirmButtonColor: '#3f88f5',
      className: 'custom-dialog',
      showCancelButton: false,
      closeOnClickOverlay: true
    })
    return false
  }
  return true
}

function validatePassword() {
  if (!postData.loginPassword) {
    showDialog({
      message: t('userpassword_newPlaceholder'),
      confirmButtonText: t('logintxt.register07'),
      confirmButtonColor: '#3f88f5',
      className: 'custom-dialog',
      showCancelButton: false,
      closeOnClickOverlay: true
    })
    return false
  }
  
  // 添加密码长度验证
  if (postData.loginPassword.length < 6) {
    showDialog({
      message: t('logintxt.register09'),
      confirmButtonText: t('logintxt.register07'),
      confirmButtonColor: '#3f88f5',
      className: 'custom-dialog',
      showCancelButton: false,
      closeOnClickOverlay: true
    })
    return false
  }
  
  return true
}

// 页面加载时获取区号
onMounted(() => {
  // 设置默认区号
  postData.areaCode = '57'
  currentAreaCode.value = '57'
  
  // 获取区号列表
  getAreaCodes()
})

async function reset() {
  // 手动验证
  if (!validatePhoneNumber() || !validateCode() || !validatePassword()) {
    return
  }
  
  try {
    loading.value = true
    
    // 构建重置密码参数
    const resetData = {
      tel: `${postData.tel}`, // 组合手机号和区号作为email参数
      code: postData.code,
      loginPassword: postData.loginPassword.replace(/\s+/g, ""),
    }
    
    // 调用重置密码API
    const res = await userStore.reset(resetData)
    
    if (res) {
      showNotify({ type: 'success', message: t('logintxt.forgot04'),  })
      router.replace('/login')
    }
  }
  catch (error: any) {
    // 处理重置失败情况
    const errorMessage = error?.message ||  t('logintxt.forgot05');
    showDialog({
      message: errorMessage,
      confirmButtonText: t('logintxt.register07'),
      confirmButtonColor: '#3f88f5',
      className: 'custom-dialog',
      showCancelButton: false,
      closeOnClickOverlay: true
    })
  }
  finally {
    loading.value = false
  }
}

const isGettingCode = ref(false)

// 验证码倒计时相关
const countdown = ref(0)
const countdownText = ref(t('logintxt.forgot08'))

// 更新倒计时文本
function updateCountdownText() {
  if (countdown.value <= 0) {
    countdownText.value = t('logintxt.forgot08')
    return
  }
  countdownText.value = `${countdown.value}s`
}

// 开始倒计时
function startCountdown(seconds = 60) {
  countdown.value = seconds
  updateCountdownText()
  
  const timer = setInterval(() => {
    countdown.value--
    updateCountdownText()
    
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

async function getCode() {
  if (!validatePhoneNumber()) {
    return
  }

  if (isGettingCode.value || countdown.value > 0) return

  isGettingCode.value = true
  
  try {
    // 构建获取验证码参数
    const codeParams = {
      account: postData.tel,
      areaCode: postData.areaCode,
      type: 'toCodeByTel' // 根据接口要求设置类型
    }
    
    
    // 调用获取验证码API - 直接传递参数
    const response = await verifyResetCode(codeParams)
    console.log('response:', response)
    
    // 假设API返回的结果结构是 { code: 0, data: {...}, message: '...' }
    // 或者整个响应就是返回的数据
    const res = response?.data || response
    
    if (res.code === 200) {
      // 显示成功提示
      showDialog({
        title: '',
        message: t('logintxt.forgot07'),
        confirmButtonText:  t('logintxt.register07'),
        confirmButtonColor: '#3f88f5',
        className: 'success-dialog',
        showCancelButton: false,
        closeOnClickOverlay: false
      })
      
      // 开始倒计时
      startCountdown(60)
    }
  } catch (error: any) {
    console.error('err:', error)
    const errorMessage = error?.message || t('logintxt.register06')
    showDialog({
      message: errorMessage,
      confirmButtonText:  t('logintxt.register07'),
      confirmButtonColor: '#3f88f5',
      className: 'custom-dialog',
      showCancelButton: false,
      closeOnClickOverlay: true
    })
  } finally {
    isGettingCode.value = false
  }
}
</script>

<style lang="less" scoped>
.loginpage{
  background-color: #221a18;
}
.reset-password {
  background-image: url('@/assets/images/login/topBg.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  min-height: 100vh;
  position: relative;
  z-index: 10;
  display: flex;
  flex-direction: column;
  
  .login-title {
    width: 100%;
    overflow: hidden;
    padding: 5px 0;
    font-size: 15px;
    color: transparent;
    background: linear-gradient(112deg, #f9f3ed 14%, #fad4b7 88%), #ffe6ce;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
    background-clip: text;
    text-fill-color: transparent;
    h3{
      margin: 0 0 15px 0;
    }
  }
}

.back-icon {
  position: absolute;
  top: 20px;
  left: 15px;
  padding: 8px;
  z-index: 100;
}

.login-logo{
  margin-left: -30px;
}

.resetmain{
  padding-top: 52px;
  display: flex;
  flex-direction: column;
  flex: 1;
  margin: 20px  30px 0 30px;
}

.reset-form{
  width: 100%;
  height: 400px;
  overflow: hidden;
  padding: 20px 15px;
  font-size: 15px;
  background: url('@/assets/images/login/loginBg.png') no-repeat top;
  background-size: 100% auto;
}

.phone-input-wrapper {
  display: flex;
  align-items: center;
  background-color: #1c1c1e;
  border-radius: 12px;
  height: 48px;
  overflow: hidden;
  border: 1px solid #d6c4a4;
}

.user-icon-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 20px;
  height: 100%;
  padding: 0 5px 0 10px;
}

.user-icon {
  width: 18px;
  height: 18px;
  object-fit: contain;
}

.phone-area-code {
  display: flex;
  align-items: center;
  padding: 0 5px 0 15px;
  height: 100%;
  color: #f6eade;
  font-size: 14px;
  font-weight: 500;
  border-right: 0px solid #d6c4a4;
  
  span {
    margin-right: 4px;
    font-size: 16px;
  }
}

.phone-input {
  flex: 1;
  background-color: transparent;
  
  :deep(.van-field__control) {
    color: #f6eade;
    padding-left: 0;
    font-size: 16px;
  }
  
  :deep(.van-field__placeholder) {
    color: rgba(255, 255, 255, 0.5);
    font-size: 16px;
  }
}

.verification-input-wrapper {
  display: flex;
  align-items: center;
  background-color: #1c1c1e;
  border-radius: 12px;
  height: 48px;
  overflow: hidden;
  border: 1px solid #d6c4a4;
}

.verification-icon-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 20px;
  height: 100%;
  padding: 0 5px 0 10px;
}

.verification-icon {
  width: 18px;
  height: 18px;
  object-fit: contain;
}

.verification-input {
  flex: 1;
  background-color: transparent;
  
  :deep(.van-field__control) {
    color: #f6eade;
    padding-left: 0;
    font-size: 16px;
  }
  
  :deep(.van-field__placeholder) {
    color: rgba(255, 255, 255, 0.5);
    font-size: 16px;
  }
  
  :deep(.van-field__right-icon) {
    padding: 0;
  }
}

.send-code-btn {
  color: #d6c4a4;
  font-size: 14px;
  padding: 0 15px;
  height: 100%;
  display: flex;
  align-items: center;
  border-left: 1px solid #333;
  
  &.disabled {
    color: #f1b42e;
    cursor: not-allowed;
  }
}

.password-input {
  background-color: #1c1c1e;
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #d6c4a4;
  height: 48px;
  padding-left: 10px;
  
  :deep(.van-field__control) {
    color: #f6eade;
    padding-left: 0;
    font-size: 16px;
  }
  
  :deep(.van-field__right-icon) {
    color: #f6eade;
    padding-right: 15px;
  }
  
  :deep(.van-field__left-icon) {
    padding: 0;
  }
  
  :deep(.van-field__placeholder) {
    color: rgba(255, 255, 255, 0.5);
    font-size: 16px;
  }
}

.password-icon-container {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 20px;
  height: 100%;
  padding: 0 25px 0 0px;
}

.password-icon {
  width: 18px;
  height: 18px;
  object-fit: contain;
}

.reset-btn {
  color: #0c1f26;
  font-weight: 500;
  background: linear-gradient(270deg, #fee5cf, #dfb695 50%, #fee5cf), linear-gradient(180deg, #af917f 2%, #a9836b 99%);
  border-radius: 12px;
  box-shadow: 0 4px 10px 0 rgba(0, 0, 0, .3);
  border: none;
  height: 44px;
  
  :deep(.van-button__content) {
    color: #0c1f26;
    font-weight: 600;
    font-size: 16px;
  }
  
  &:active {
    opacity: 0.9;
  }
  
  &.van-button--loading {
    .van-loading__spinner {
      color: #0c1f26;
    }
  }
}

.privacy-policy-container {
  width: 100%;
  text-align: center;
  padding: 16px 0;
  position: fixed;
  bottom: 0;
  left: 0;
}

.privacy-policy-link {
  color: #d6c4a4;
  opacity: 0.8;
  font-size: 12px;
  text-decoration: none;
  
  &:hover {
    text-decoration: underline;
  }
}
.fortips{
  color: #999999;
  font-size: 11px;
  margin: 10px 0 5px 0;
}

:deep(.success-dialog) {
  background-color: #ffffff !important;
  border-radius: 8px !important;
  
  .van-dialog__header {
    display: none;
  }
  
  .van-dialog__content {
    color: #333 !important;
    padding: 30px 20px;
  }
  
  .van-dialog__message {
    color: #333 !important;
    font-size: 16px;
    padding: 0;
    text-align: center;
  }
  
  .van-button {
    height: 40px;
    font-size: 16px;
    border-radius: 6px;
  }
  
  .van-dialog__footer {
    padding: 0 20px 20px;
  }
}
</style>
